import axios from "axios";
import {Message} from 'element-ui'
import router from "@/router";

const service = axios.create({
    baseURL: '/api',
    timeout: 3000
})

service.interceptors.request.use((config) => {
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem("token")
    return config
}, (error) => {
    return Promise.reject(error)
})

service.interceptors.response.use((response) => {
    if (response.status === 200) {
        let {code, msg} = response.data
        if (code === 500) {
            Message({message: msg || '服务器异常', type: 'error'})
        }
        if (code === 200) {
            return response.data
        }
    }
}, (error) => {
    if (error.response.status === 401) {
        router.push('/login')
    } else {
        return Promise.reject(error)
    }
})
export default service
